package com.zhuangwei;

import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zhuangwei.entity.Course;
import com.zhuangwei.entity.Student;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zwx
 */
@RestController
@SpringBootApplication
@Configuration
public class SpringBootDemoHelloWorldApplication {
    @Value("${spring.boot.demo.helloworld.data.version}")
    private String version;
    @Value("${author}")
    String author;
    @Value("${exclusions}")
    String exclusions;
    @Value("${connectionProperties}")
    String connectionProperties;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoHelloWorldApplication.class, args);
    }

    @GetMapping("/hello")
    public Map<String, Object> sayHello() {
        Map<String, Object> result = Maps.newHashMap();
        result.put("ret", true);
        result.put("msg", StrUtil.format("hello,world,{}", author));
        Map<String, Object> data = Maps.newHashMap();
        data.put("version", version);
        data.put("exclusions", exclusions.split(","));
        Map<String, Object> connectionProperty = Maps.newHashMap();
        for (String connection : connectionProperties.split(";")) {
            String[] conn = connection.split("=");
            connectionProperty.put(conn[0], conn[1]);
        }
        data.put("connectionProperties", connectionProperty);
        result.put("data", data);
        return result;
    }


    @InitBinder("student")
    public void initBinderStudent(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("student.");
    }

    @InitBinder("course")
    public void initBinderCourse(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("course.");
    }

    @PostMapping("/test")
    public Map<String, Object> test(@ModelAttribute("student") Student student, @ModelAttribute("course") Course course) {
        HashMap<String, Object> som = new HashMap<>(2);
        som.put("student", student);
        som.put("course", course);
        return som;
    }
}